using System.Text.Json;

namespace UniversalAdminSystem.Infrastructure.Services;

public class SpaCyService
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl = "http://flaskapi:5000";
    // private readonly string _baseUrl = "http://127.0.0.1:5000";


    // 构造函数，注入 IHttpClientFactory
    public SpaCyService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("SpaCyClient");
        _httpClient.BaseAddress = new Uri(_baseUrl);
    }

    // 发送请求到 Flask API 获取 文本分析 结果
    public async Task<PreprocessResult> AnalyzeTextAsync(string text)
    {
        HttpRequestMessage request;
        HttpResponseMessage response;
        try
        {
            // 构造请求内容
            request = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/spacy")
            {
                Content = new StringContent(JsonSerializer.Serialize(new { text }), System.Text.Encoding.UTF8, "application/json")
            };

            // 发送请求
            response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None);
            response.EnsureSuccessStatusCode();

            // 读取响应内容
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Response from Flask: " + result);  // 打印响应数据，方便调试

            // 解析响应 JSON
            var preprocessResult = JsonSerializer.Deserialize<PreprocessResult>(result);
            Console.WriteLine("preprocessResult: " + preprocessResult);

            if (preprocessResult != null && preprocessResult.Entities.Count > 0)
            {
                // 打印解析后的对象（调试）
                Console.WriteLine("Entities:");
                foreach (var entity in preprocessResult.Entities)
                {
                    Console.WriteLine($"Text: {entity.Text}, Label: {entity.Label}");
                }

                Console.WriteLine("\nSentences:");
                foreach (var sentence in preprocessResult.Sentences)
                {
                    Console.WriteLine(sentence);
                }
            }

            return preprocessResult ?? throw new Exception("文本预处理错误");
        }
        catch (Exception ex)
        {
            // 处理错误，例如网络问题或 API 服务不可用
            Console.WriteLine($"Error: {ex.Message}");
            throw;
        }
    }

    // 发送请求到 Flask API 获取 用户输入解析 结果
    public async Task<UserInputParseResult> ParseUserInputAsync(string userInput)
    {
        HttpRequestMessage request;
        HttpResponseMessage response;
        try
        {
            // 构造请求内容
            request = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/parse_input")
            {
                Content = new StringContent(JsonSerializer.Serialize(new { content = userInput }), System.Text.Encoding.UTF8, "application/json")
            };

            // 发送请求
            response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None);
            response.EnsureSuccessStatusCode();

            // 读取响应内容
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Response from Flask: " + result);  // 打印响应数据，方便调试

            // 解析响应结果
            var userInputParseResult = JsonSerializer.Deserialize<UserInputParseResult>(result, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            return userInputParseResult ?? throw new Exception("文本预处理错误");
        }
        catch (Exception ex)
        {
            // 处理错误，例如网络问题或 API 服务不可用
            Console.WriteLine($"Error: {ex.Message}");
            throw;
        }
    }
}

// 预处理结果类
public class PreprocessResult
{
    public List<Entity> Entities { get; set; } = [];
    public List<string> Sentences { get; set; } = [];
}

// 实体类
public class Entity
{
    public string Text { get; set; } = string.Empty;
    public string Label { get; set; } = string.Empty;
}

// 用户输入解析结果类
public class UserInputParseResult
{
    public string Text { get; set; } = string.Empty;
    public List<Entity> Entities { get; set; } = [];
    public List<string> Tokens { get; set; } = [];
}